package web.servlet.question;

import com.fasterxml.jackson.databind.ObjectMapper;
import domain.PageBean;
import domain.Question;
import domain.response.FindQuestionByPageResponse;
import service.QuestionService;
import service.impl.QuestionServiceImpl;
import utils.LyyLogUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/queryQuestionByPage")
public class FindQuestionByPageServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=utf-8");
        QuestionService service=new QuestionServiceImpl();
        Exception exception=null;
        List<Question> list=null;
        FindQuestionByPageResponse findQuestionByPageResponse=new FindQuestionByPageResponse();
        try {
            list = service.queryByPage(request);
        } catch (Exception e) {
            exception=e;
            LyyLogUtil.logeE(e.getMessage());
        }
        if(exception!=null){
            findQuestionByPageResponse.setErrMsg(exception.getMessage());
            findQuestionByPageResponse.setStatus(0);
        }else {
            PageBean<Question> questionPageBean = new PageBean<>();
            questionPageBean.setDataList(list);
            questionPageBean.setCurrPage(Integer.parseInt(request.getParameter("currPage")));
            int pageSize = Integer.parseInt(request.getParameter("pageSize"));
            questionPageBean.setPageSize(pageSize);
            int totalCount = 0;
            try {
                totalCount = service.queryTotalCount(request);
            } catch (Exception e) {
                exception=e;
                LyyLogUtil.logeE(e.getMessage());
            }
            LyyLogUtil.logD("查询到的总记录数为："+totalCount);
            questionPageBean.setTotalCount(totalCount);
            questionPageBean.setTotalPage(totalCount%pageSize==0?totalCount/pageSize:(totalCount/pageSize+1));
            if(exception!=null){
                findQuestionByPageResponse.setErrMsg(exception.getMessage());
                findQuestionByPageResponse.setStatus(0);
            }else {
                findQuestionByPageResponse.setPageBean(questionPageBean);
            }

        }
        ObjectMapper objectMapper=new ObjectMapper();
        objectMapper.writeValue(response.getOutputStream(),findQuestionByPageResponse);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}
